package edu.hawaii.ics499;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class SensorActivity extends Activity implements SensorEventListener {
  
  //Global variables
  private Handler handler;
  private SensorManager mSensorManager;
  private Sensor accelerometer;
  private TextView text1;
  private TextView text3;
  private Button b_data;
  private Button b_getAverage;
  private DatabaseHelper db;
  private SQLiteDatabase qdb;
  private boolean gettingAverage = false;
  
  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      
      //Access the sensors
      mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
      //Get the ACCELEROMETER sensor from the device
      accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
      
      //Connect to the database
      db = new DatabaseHelper(this);
      qdb = db.getWritableDatabase();
      
      handler = new Handler();
      
      //Initialize the widgets in the layout
      text1 = (TextView) findViewById(R.id.text1);
      b_data = (Button) findViewById(R.id.b_data);
      b_getAverage = (Button) findViewById(R.id.b_getAverage);
      text3 = (TextView) findViewById(R.id.text3);
      
      //Create a listener for the button
      b_data.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          //Switch to the 'DataPreviewActivity' activity
          Intent intent = new Intent(SensorActivity.this, DataPreviewActivity.class);
          startActivity(intent);
        }
      });
      
      b_getAverage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
         gettingAverage = !gettingAverage;
         if(gettingAverage) {
           b_getAverage.setText("Stop Average Calculation");
           startGettingAverage();
         }
         else{
           b_getAverage.setText("Start Average Calculation");
         }
        }
      });
  }
  
  /**
   * Called when the sensor's accuracy changed
   */
  @Override
  public void onAccuracyChanged(Sensor arg0, int arg1) {
    // TODO Auto-generated method stub
    
  }
  
  /**
   * Called when the sensor data changes
   */
  @Override
  public void onSensorChanged(SensorEvent event) {
    //Only check for the accelerometer sensor data (3 values) 
    if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
      //Get the first value
      float data = event.values[0];
      //Show that on the screen
      text1.setText("" + data);
      //Execute an INSERT sql query
      String sql = "INSERT INTO accelerometer (data, timestamp) " +
          "VALUES ( " + data + ",'" + getTime() +  "')";
      qdb.execSQL(sql);
      }
  }
  
  /**
   * Register the sensor when the application is opened
   */
  @Override
  public void onResume () {
    super.onResume();
    //With normal delay
    mSensorManager.registerListener(this, accelerometer, 1000000);
  }
  
  /**
   * Unregister the sensor when the application is closed
   */
  @Override
  public void onPause () {
    super.onPause();
    mSensorManager.unregisterListener(this);
  }
  
  public String getTime () {
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    return dateFormat.format(cal.getTime());
  }
  
  /**
   * Thread to run a sql query
   * Code inspired from http://www.vogella.com/articles/AndroidPerformance/article.html
   * @param view
   */
  public void startGettingAverage() {
    // Do something long
    Runnable runnable = new Runnable() {
      @Override
      public void run() {
        while(gettingAverage){
          final Cursor cursor = qdb.rawQuery("SELECT AVG(data) from accelerometer", null);
          cursor.moveToFirst();
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          handler.post(new Runnable() {
            @Override
            public void run() {
              if(gettingAverage)
                text3.setText(cursor.getFloat(0) + "\n");
              else
                text3.setText("");
            }
          });
        }
      }
    };
    new Thread(runnable).start();
  }
}
